<template>
  <div class="account-security">
    <h2>账号安全</h2>
    <el-tabs v-model="activeTab">
      <el-tab-pane label="身份证信息" name="idCard">
        <el-form label-width="120px">
          <el-form-item label="身份证号码">
            <el-input v-model="userInfo.idCard" disabled></el-input>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="修改密码" name="password">
        <el-form :model="form" :rules="rules" label-width="120px" ref="passwordForm">
          <el-form-item label="旧密码" prop="oldPassword">
            <el-input v-model="form.oldPassword" type="password" show-password></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="form.newPassword" type="password" show-password></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="form.confirmPassword" type="password" show-password></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm">保存</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const activeTab = ref('idCard')
const passwordForm = ref(null)
const userInfo = ref({
  idCard: ''
})

const form = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// const username = localStorage.getItem('username')
const userStr = localStorage.getItem('user');
if (!userStr) {
  throw new Error('未获取到用户信息');
}

// ✅ 解析 JSON 并提取 username
const userData = JSON.parse(userStr);
const username = userData.user.username;
// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const response = await axios.get(BASE_URL + '/api/volunteer/userInfo', {
      params: { username }
    })
    userInfo.value = response.data.data
  } catch (error) {
    ElMessage.error('获取用户信息失败')
  }
}

const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== form.newPassword) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const rules = reactive({
  oldPassword: [
    {required: true, message: '请输入旧密码', trigger: 'blur'}
  ],
  newPassword: [
    {required: true, message: '请输入新密码', trigger: 'blur'},
    {min: 6, max: 20, message: '长度在6到20个字符', trigger: 'blur'}
  ],
  confirmPassword: [
    {required: true, message: '请确认密码', trigger: 'blur'},
    {validator: validatePass, trigger: 'blur'}
  ]
})

const submitForm = async () => {
  try {
    // 验证表单
    await passwordForm.value.validate()

    const data = {
      username,
      oldPassword: form.oldPassword,
      newPassword: form.newPassword
    }

    await axios.post(BASE_URL + '/api/volunteer/updatePassword', data, {
      headers: {
        'Content-Type': 'application/json'
      }
    })

    ElMessage.success('密码修改成功')
    form.oldPassword = ''
    form.newPassword = ''
    form.confirmPassword = ''
  } catch (error) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('密码修改失败')
    }
  }
}

// 组件挂载时获取用户信息
onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.account-security {
  padding: 20px;
}
</style>